import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import { query, updateUsername, verifyUserPassword, updatePassword } from '../db.js';
import config from '../config.js';

// 用户注册
const register = async (req, res) => {
  try {
    const { username, email, password } = req.body;
    
    // 检查邮箱是否已被注册
    const emailExist = await query('SELECT * FROM users WHERE email = ?', [email]);
    if (emailExist.length > 0) {
      return res.status(400).json({ message: '邮箱已被注册' });
    }
    
    // 加密密码
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(password, salt);
    
    // 保存用户到数据库
    const sql = 'INSERT INTO users (username, email, password) VALUES (?, ?, ?)';
    await query(sql, [username, email, hashedPassword]);
    
    // 获取新创建的用户ID
    const result = await query('SELECT id FROM users WHERE email = ?', [email]);
    const userId = result[0].id;
    
    // 创建并返回JWT token
    const token = jwt.sign({ id: userId }, config.jwt.secret, { expiresIn: config.jwt.expiresIn });
    
    res.status(201).json({
      message: '注册成功',
      token,
      user: {
        id: userId,
        username,
        email
      }
    });
  } catch (error) {
    console.error('注册失败:', error);
    res.status(500).json({ message: '服务器错误，请稍后再试' });
  }
};

// 用户登录
const login = async (req, res) => {
  try {
    const { email, password } = req.body;
    
    // 检查邮箱是否存在
    const users = await query('SELECT * FROM users WHERE email = ?', [email]);
    if (users.length === 0) {
      return res.status(400).json({ message: '邮箱或密码不正确' });
    }
    
    const user = users[0];
    
    // 验证密码
    const validPassword = await bcrypt.compare(password, user.password);
    if (!validPassword) {
      return res.status(400).json({ message: '邮箱或密码不正确' });
    }
    
    // 创建并返回JWT token
    const token = jwt.sign({ id: user.id }, config.jwt.secret, { expiresIn: config.jwt.expiresIn });
    
    res.json({
      message: '登录成功',
      token,
      user: {
        id: user.id,
        username: user.username,
        email: user.email
      }
    });
  } catch (error) {
    console.error('登录失败:', error);
    res.status(500).json({ message: '服务器错误，请稍后再试' });
  }
};

// 验证用户token
const verifyToken = (req, res) => {
  const token = req.headers.authorization?.split(' ')[1];
  
  if (!token) {
    return res.status(401).json({ message: '未提供授权令牌' });
  }
  
  try {
    const decoded = jwt.verify(token, config.jwt.secret);
    res.json({ valid: true, userId: decoded.id });
  } catch (error) {
    res.status(401).json({ valid: false, message: '授权令牌无效或已过期' });
  }
};

// 更新用户名
const changeUsername = async (req, res) => {
  try {
    const userId = req.user.id; // 假设有中间件已经验证并设置了req.user
    const { username } = req.body;
    
    if (!username || username.trim() === '') {
      return res.status(400).json({ message: '用户名不能为空' });
    }
    
    // 更新用户名
    const success = await updateUsername(userId, username);
    
    if (success) {
      res.json({ message: '用户名更新成功', username });
    } else {
      res.status(404).json({ message: '用户不存在或更新失败' });
    }
  } catch (error) {
    console.error('更新用户名失败:', error);
    res.status(500).json({ message: '服务器错误，请稍后再试' });
  }
};

// 修改密码
const changePassword = async (req, res) => {
  try {
    const userId = req.user.id; // 假设有中间件已经验证并设置了req.user
    const { currentPassword, newPassword } = req.body;
    
    if (!currentPassword || !newPassword) {
      return res.status(400).json({ message: '当前密码和新密码不能为空' });
    }
    
    // 获取用户信息
    const users = await query('SELECT * FROM users WHERE id = ?', [userId]);
    if (users.length === 0) {
      return res.status(404).json({ message: '用户不存在' });
    }
    
    const user = users[0];
    
    // 验证当前密码
    const validPassword = await bcrypt.compare(currentPassword, user.password);
    if (!validPassword) {
      return res.status(400).json({ message: '当前密码不正确' });
    }
    
    // 加密新密码
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(newPassword, salt);
    
    // 更新密码
    const success = await updatePassword(userId, hashedPassword);
    
    if (success) {
      res.json({ message: '密码更改成功' });
    } else {
      res.status(404).json({ message: '更新密码失败' });
    }
  } catch (error) {
    console.error('更改密码失败:', error);
    res.status(500).json({ message: '服务器错误，请稍后再试' });
  }
};

export {
  register,
  login,
  verifyToken,
  changeUsername,
  changePassword
}; 